﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Microsoft.Practices.ServiceLocation;

namespace Dynamic_UI_Framework
{
    [Export(typeof(ElementController))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class ElementController
    {
        public ElementController()
        {
            foreach (var part in (ServiceLocator.Current as MefServiceLocator).CompositionContainer.Catalog.Parts)
            {
                foreach (var ed in part.ExportDefinitions)
                {
                    object type = ed.Metadata["ExportTypeIdentity"];
                    if (type.ToString().Equals(typeof(IElement).FullName))
                    {
                        ElementNode node = new ElementNode { ContractName = ed.ContractName, ExportTypeIdentity = type.ToString() };
                        if (Nodes == null)
                            Nodes = new List<ElementNode>();
                        Nodes.Add(node);
                    }
                }
            }


        }

        public void Mapping()
        {
            if (Nodes == null)
                return;

            ElementAdapterMapping elementAdapterMappings = ServiceLocator.Current.GetInstance<ElementAdapterMapping>();
            if (elementAdapterMappings != null)
            {
                foreach (var item in Nodes)
                {
                    elementAdapterMappings.RegisterMapping(item.ContractName, ServiceLocator.Current.GetInstance<ElementAdapter>());
                }
            }
        }

        public List<ElementNode> Nodes { get; private set; }
        public class ElementNode
        {
            public string ContractName { get; set; }
            public string ExportTypeIdentity { get; set; }
        }
    }

}
